package org.massdeception.content.servlets;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.massdeception.content.entities.Slide;
import org.massdeception.content.util.SlideUtils;

public class StreamSlideServlet extends HttpServlet
{    
    private static final Logger log = Logger.getLogger(StreamSlideServlet.class.getName());
    
    private static HashMap<String, String> mimeTypes;
    
    public void init(ServletConfig config) throws ServletException
    {
        try
        {
            mimeTypes = new HashMap<String, String>();
            mimeTypes.put("gif", "image/gif");
            mimeTypes.put("jpeg", "image/jpeg");
            mimeTypes.put("jpg", "image/jpeg");
            mimeTypes.put("png", "image/png");
        }
        catch (Throwable t)
        {
            log.log(Level.SEVERE, "Could not load mime type map", t);
        }        
    }
    
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException
    {
        try
        {
            String date = request.getPathInfo();
            
            // strip the leading slash
            date = date.substring(1, date.indexOf("."));
            
            Long normDate = SlideUtils.getNormalizedDate(date, false);
            Long today = SlideUtils.getNormalizedDate(new Date(), true);
            
            //log.log(Level.WARNING, "requested: "+dateFormatted+", now: "+current);
            
            if ( normDate > today )
            {
                log.log(Level.WARNING, "Future date was requested, not serving.");
                response.sendError(404, "Could not find requested slide.");
                return;
            }
            
            Slide slide = SlideUtils.getSlideByDay(normDate);
            
            //log.log(Level.WARNING, "#### slide: "+slide.getId());
            
            response.setContentType(mimeTypes.get(slide.getExtension()));
            response.setHeader("Content-length", Long.toString(slide.getBytes().length));
            
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(slide.getBytes());
            outputStream.close();
        }
        catch (Throwable t)
        {
            log.log(Level.WARNING, "Could not find slide.", t);
            response.sendError(404, "Could not find slide.");
        }
    }
}